package com.hand.wfive.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Point
import android.os.Bundle
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.hand.wfive.R
import com.hand.wfive.activity.PrivacyActivity
import com.hand.wfive.util.SpanUtils

import kotlinx.android.synthetic.main.dialog_buy_protocal_tips.*

/**
 * 购买协议提示弹窗
 */
class BuyProtocolTipDialog(
    context: Context,
    private var mListener: TipListener?,
) : Dialog(
    context, R.style.CustomDialog) {

    companion object {
        fun showDialog(context: Context , listener: TipListener?) {
            BuyProtocolTipDialog(context ,listener).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.dialog_buy_protocal_tips)
        setWidth()
        //按空白处不能取消动画
        setCanceledOnTouchOutside(false)
        setCancelable(false)
        //初始化界面控件的事件
        initEvent()
    }

    private fun setWidth() {
        //设置宽度
        val m = window?.windowManager
        val d = m?.defaultDisplay
        val p = window?.attributes
        val size = Point()
        d?.getSize(size)
        p?.width = (size.x * 0.75).toInt() //设置dialog的宽度为当前手机屏幕的宽度*0.8
        window?.attributes = p
    }

    /**
     * 初始化界面的确定和取消监听器
     */
    private fun initEvent() {
        setProtocolStyle()
        //设置取消按钮被点击后，向外界提供监听
        tvCancel.setOnClickListener { v: View? ->
            dismiss()
        }
        tvOpenVip.setOnClickListener { v: View? ->
            mListener?.doBuy()
            dismiss()
        }
    }

    private fun setProtocolStyle() {
        val sp = SpanUtils()
        sp.append("我已阅读并同意")
            .append("《购买协议》").setForegroundColor(ContextCompat.getColor(context, R.color.orange_ECAB5E))
            .setClickSpan(object : ClickableSpan() {
                override fun onClick(widget: View) {
                    PrivacyActivity.showRule(context, PrivacyActivity.VIPRULE)
                }

                override fun updateDrawState(ds: TextPaint) {
                    ds.color = ContextCompat.getColor(context, R.color.orange_ECAB5E)
                    ds.isUnderlineText = true
                }
            })
        tvContent.text = sp.create()
        tvContent.movementMethod = LinkMovementMethod.getInstance()
        tvContent.highlightColor = Color.TRANSPARENT // 设置点击无颜色
    }

    interface TipListener {
        fun doBuy()
    }
}